#include "dbg/log.h"
#include "os/thread.h"
#include "control.h"

static float g_song_position = 0.0f;
static bool g_song_position_changed = false;

static float g_song_position_in_secs = 0.0f;
static float g_current_song_length = 100.0f;

enum Mode
{
	mode_stopped,
	mode_playing,
	mode_paused
};

static Mode g_mode = mode_stopped;

void control_thread()
{
	while (true)
	{
		Sleep(10);

		if (g_mode == mode_playing)
		{
			float time_passed = 0.01f;

			g_song_position_in_secs += time_passed;
			if (g_song_position_in_secs > g_current_song_length)
				g_song_position_in_secs = 0.0f;

			song_position(g_song_position_in_secs / g_current_song_length);
		}
	}
}

void start_control_thread()
{
	Thread::start_thread(control_thread);
}

// Query song position (0..1)
float song_position()
{
	return g_song_position;
}

// Set song position (0..1)
void song_position(float value)
{
	g_song_position = value;
	g_song_position_changed = true;

	// Actually start to decode from a given sample position
	g_song_position_in_secs = g_song_position * g_current_song_length;
}

// Has song position changed since we last asked?
bool song_position_changed()
{
	bool result = g_song_position_changed;

	g_song_position_changed = false;
	return result;
}

void play()
{
	g_mode = mode_playing;
}

void pause()
{
	g_mode = mode_paused;
}

void stop()
{
	g_mode = mode_stopped;
	song_position(0.0f);
}
